

var allPlacesSequence;
var obligatoryPlaces=[];
var selectablePlaces=[];
var showDetailedLinkCount=0;

console.log(transferSecondToTime(8630),transferSecondToTime(250),transferSecondToTime(45));

//当点击route plan tab或者按钮时调用
function routePlanInit() {
    obligatoryPlaces=[];
    selectablePlaces=[];
    //返回编辑按钮监听
    $("#formVerifyTips span:eq(0)").on('click',function () {
       $("#taskListTab").trigger("click");
    });

    //获取全部节点信息
    $.ajax({
        type:"get",
       // url:"http://localhost:8779/edge/findAllPlaces",
        url:"http://"+domainIp+':' + port + "/task-assign/single-route-plan/findAllPlaces",
        async:false,
        dataType: "json",
        success:function(allPlacesJson){
            if (allPlacesJson.code===200){
                allPlacesSequence=allPlacesJson.data;
            }
            //当服务挂掉并且被注册中心移除时，或者服务未启动注册时
            else{
                exceptionLayer(allPlacesJson.msg);
            }
        },
        //当服务挂掉但尚未从注册中心移除时
        error:function (errorInfo) {
            exceptionLayer(errorInfo.responseText);
        }
    });

    //给文本域增加内容
    fillFormTextAreaAndSwitch();

    //给表单添加验证
    formVerify();

    //表单提交
    formSubmit();
}

//帮助链接增加监听
function applyActionToHelpTips() {
    for(var i=0;i<$(".placeTips").length;i++){
        if(i===0||i===1){
            $(".placeTips:eq("+i+")").on('click',function () {
                layer.open({
                    title:'Tips',
                    btn:'okay',
                    content:'<cite style="color: red">必经节点</cite>是必须要抵达的节点'
                })
            })
        }
        else{
            $(".placeTips:eq("+i+")").on('click',function () {
                layer.open({
                    title:'Tips',
                    btn:'okay',
                    content:'<cite style="color: red">可选节点</cite>是优先级为1或2的节点'
                })
            })
        }
    }
}

//对于文本域和开关进行初始化
function fillFormTextAreaAndSwitch(){
    layui.use(['layer','form'],function () {
        //对于文本域的填充
        var layer=layui.layer,form=layui.form;
        $.ajax({
            type:'get',
            async:false,
            // url:'http://localhost:8779/edge/findObligatoryPlaces',
            url:'http://'+domainIp+':' + port + '/task-assign/single-route-plan/findObligatoryPlaces',
            success:function (obligatoryPlacesJson) {
                if (obligatoryPlacesJson.code===200){
                    if(obligatoryPlacesJson.data.length===0){
                        form.val('paramConfirmForm_filter',{
                            "obligatoryArea":"未给出"
                        })
                    }
                    else{
                        var obligatoryContent="";
                        for(var i=0;i<obligatoryPlacesJson.data.length;i++){
                            if(i!==obligatoryPlacesJson.data.length-1){
                                obligatoryContent=obligatoryContent+obligatoryPlacesJson.data[i].id+", ";
                            }
                            else {
                                obligatoryContent=obligatoryContent+obligatoryPlacesJson.data[i].id
                            }

                            //将数据加入数组
                            obligatoryPlaces.push(obligatoryPlacesJson.data[i].id);
                        }
                        form.val('paramConfirmForm_filter',{
                            "obligatoryArea":obligatoryContent,
                        })
                    }
                }
                else{
                    // layer.alert(obligatoryPlacesJson.msg,{
                    //     title:'Message',btn:'okay'
                    // });
                    exceptionLayer(obligatoryPlacesJson.msg);
                }
            },
            error:function (errorInfo) {
                // layer.alert(errorInfo.responseText,{
                //     title:'Message',btn:'okay'
                // });
                exceptionLayer(errorInfo.responseText);
            }
        });
        $.ajax({
            type:'get',
            async:false,
            // url:'http://localhost:8779/edge/findSelectablePlaces',
            url:'http://'+domainIp+':' + port + '/task-assign/single-route-plan/findSelectablePlaces',
            success:function (selectablePlacesJson) {
                if (selectablePlacesJson.code===200){
                    if(selectablePlacesJson.data.length===0){
                        $("#submitRouteFormBtn").attr("disabled","disabled");
                        $("#submitRouteFormBtn").addClass("layui-btn-disabled");
                        $("#selectableArea").css("border","1px solid red");
                        layer.alert("You have not specified <cite style='color: red'>Selectable Places</cite>, which is not allowed.",{
                            title:'Warning',btn:'okay'
                        });
                        form.val('paramConfirmForm_filter',{
                            "selectableArea":"未给出！此部分必须给出！！！",
                        })

                    }
                    else {
                        $("#selectableArea").css("border","");
                        $("#submitRouteFormBtn").removeAttr("disabled");
                        $("#submitRouteFormBtn").removeClass("layui-btn-disabled");
                        // $("#selectableArea").css("border","");
                        var selectableContent="";
                        for(var i=0;i<selectablePlacesJson.data.length;i++){
                            if(i!==selectablePlacesJson.data.length-1){
                                selectableContent=selectableContent+selectablePlacesJson.data[i].id+", ";
                            }
                            else {
                                selectableContent=selectableContent+selectablePlacesJson.data[i].id
                            }

                            //将数据加入数组
                            selectablePlaces.push(selectablePlacesJson.data[i].id);
                        }
                        form.val('paramConfirmForm_filter',{
                            "selectableArea":selectableContent,
                        })
                    }
                }
                else{
                    // layer.alert(selectablePlacesJson.msg,{
                    //     title:'Message',btn:'okay'
                    // });
                    exceptionLayer(selectablePlacesJson.msg);
                }

            },
            error:function (errorInfo) {
                // layer.alert(errorInfo.responseText,{
                //     title:'Message',btn:'okay'
                // });
                exceptionLayer(errorInfo.responseText);
            }
        });


        //对于开关的填充
        form.on('switch(machineLearningSwitch)',function (data) {
            if(data.elem.checked===true){
                layer.tips("使用机器学习算法进行路径规划",data.othis);
            }
            else{
                layer.tips("不使用机器学习算法",data.othis);
            }
            // console.log(data.elem.checked);

        })
    });
}

//自定义表单验证
function formVerify(){
    layui.use('form',function () {
        var form=layui.form;
        form.verify({
            required:function (value) {
                if(value===""||value===null){
                    return '输入值不可为空';
                }
            },
            startPlace:function (value) {
                var regInt=/^\d+$/;
                if(regInt.test(value)===false){
                    return '输入值必须是整数';
                }
                else {
                    var check=false;
                    for(var i=0;i<selectablePlaces.length;i++){
                        if(parseInt(value)===parseInt(selectablePlaces[i])){
                            check=true;
                        }
                    }
                    if(check===false){
                        return 'Start Place should be included in <cite style="color: red">Selectable Places</cite>';
                    }
                }
            }
        })
    })
}

//对于表单的提交
function formSubmit() {
    layui.use('form',function () {
        var form=layui.form;
        form.on('submit(submitRouteFormBtn)',function (formData) {
            // console.log(formData.field.startPlace);
            // console.log(formData.field.hasOwnProperty("machineLearningFlag"));
            //判断是否使用机器学习
            //机器学习模式
            if(formData.field.hasOwnProperty("machineLearningFlag")){
                var startPlace={};
                layer.msg("<i class=\"layui-icon layui-anim layui-anim-rotate layui-anim-loop\">&#xe63d</i>");
                //找到起点信息
                $.ajax({
                    type:"get",
                    async:false,
                    // url:"http://localhost:8779/edge/getPlaceById",
                    url:"http://"+domainIp+':' + port + '/task-assign/single-route-plan/getPlaceById',
                    data: {
                        id: formData.field.startPlace
                    },
                    success:function (rcvPlaceJson) {
                        if (rcvPlaceJson.code===200){
                            startPlace=rcvPlaceJson.data;
                            //确认最终路径
                            $.ajax({
                                type:"get",
                                async:true,
                                //url:"http://localhost:8779/edge/opsRoute",
                                url:"http://"+domainIp+':' + port + '/task-assign/single-route-plan/opsRoute',
                                data:{
                                    jing:startPlace.jing,
                                    wei:startPlace.wei,
                                    returnMode:formData.field.returnMode,
                                    machineLearningMode:1
                                },
                                success:function (rcvSeqJson) {
                                    if (rcvSeqJson.code===200){
                                        // console.log(rcfSeqJson);
                                        routePlanLayer(rcvSeqJson.data,1)
                                    }
                                    else{
                                        layer.alert(rcvSeqJson.msg,{
                                            title:'Message',btn:'okay'
                                        });
                                    }
                                },
                                error:function (errorInfo) {
                                    layer.alert(errorInfo.responseText,{
                                        title:'Message',btn:'okay'
                                    });
                                }
                            })
                        }
                        else{
                            layer.alert(rcvPlaceJson.msg,{
                                title:'Message',btn:'okay'
                            });
                        }
                    },
                    error:function (errorInfo) {
                        layer.alert(errorInfo.responseText,{
                            title:'Message',btn:'okay'
                        });
                    }
                });

            }
            //非机器学习模式
            else{
                var startPlace={};
                //得到起点信息
                $.ajax({
                    type:"get",
                    async:false,
                    // url:"http://localhost:8779/edge/getPlaceById",
                    url:"http://"+domainIp+':' + port + "/task-assign/single-route-plan/getPlaceById",
                    data:{
                        id:formData.field.startPlace
                    },
                    success:function (rcvPlaceJson) {
                        if (rcvPlaceJson.code===200){
                            // console.log(msg);
                            startPlace=rcvPlaceJson.data;
                            //得到最终路径
                            $.ajax({
                                type:"get",
                                async:false,
                                // url:"http://localhost:8779/edge/opsRoute",
                                url:"http://"+domainIp+':' + port + '/task-assign/single-route-plan/opsRoute',
                                data:{
                                    jing:startPlace.jing,
                                    wei:startPlace.wei,
                                    returnMode:formData.field.returnMode,
                                    machineLearningMode:0
                                },
                                success:function (rcvSequenceJson) {
                                    if (rcvSequenceJson.code===200){
                                        routePlanLayer(rcvSequenceJson.data,0);
                                    }
                                    else{
                                        // layer.alert(rcvSequenceJson.msg,{
                                        //     title:'Message',btn:'okay'
                                        // });
                                        exceptionLayer(rcvSequenceJson.msg);
                                    }
                                },
                                error:function (errorInfo) {
                                    // layer.alert(errorInfo.responseText,{
                                    //     title:'Message',btn:'okay'
                                    // });
                                    exceptionLayer(errorInfo.responseText);
                                }
                            });
                        }
                        else{
                            // layer.alert(rcvPlaceJson.msg,{
                            //     title:'Message',btn:'okay'
                            // });
                            exceptionLayer(rcvPlaceJson.msg);
                        }
                    },
                    error:function (errorInfo) {
                        // layer.alert(errorInfo.responseText,{
                        //     title:'Message',btn:'okay'
                        // });
                        exceptionLayer(errorInfo.responseText);
                    }
                });

            }

            return false;
        })
    })
}

function routePlanLayer(routeSequence,machineLearningMode) {
    // console.log(routeSequence);
    // console.log(checkInArray(routeSequence[0].id,obligatoryPlaces));
    //判断是否为机器学习模式
    var layerContent="";
    //非机器学习弹出层
    if(machineLearningMode===0){
        layerContent=
            '<fieldset id="routeSequenceFieldset" class="layui-elem-field layui-field-title">' +
            '   <legend>路径结果<cite>（不使用机器学习算法）</cite></legend>' +
            '</fieldset>' +
            '<div id="detailedRouteContainer"></div>' +
            '<div id="showRouteWithTimeLinkContainer">' +
            '   <a>展示路径<cite>（动态时间窗）</cite></a>' +
            '</div>' +
            '<fieldset id="routeDiagramFieldset" class="layui-elem-field layui-field-title">' +
            '   <legend>路径图<cite>（不使用机器学习算法）</cite></legend>' +
            '</fieldset>' +
            '<div id="routeDiagramContainer"></div>';
        //开启弹出层
        layer.open({
            type:1,
            title:false,
            btn:['close'],
            btn1:function(index,layero){
                layer.closeAll();
            },
            closeBtn:0,
            id:'routePlanLayui_layer',
            area:['700px','580px'],
            shade:0.1,
            move:false,
            content: layerContent
        });

    }
    //机器学习弹出层
    else{
        layerContent=
            '<fieldset id="routeSequenceFieldset" class="layui-elem-field layui-field-title">' +
            '   <legend>路径结果<cite style="color: red">（使用机器学习算法）</cite></legend>' +
            '</fieldset>' +
            '<div id="detailedRouteContainer"></div>' +
            '<div id="showRouteWithTimeLinkContainer">' +
            '   <a>展示路径<cite>（动态时间窗）</cite></a>' +
            '</div>' +
            '<fieldset id="routeDiagramFieldset" class="layui-elem-field layui-field-title">' +
            '   <legend>路径图<cite style="color: red">（使用机器学习算法）</cite></legend>' +
            '</fieldset>' +
            '<div id="routeDiagramContainer"></div>';

        //开启弹出层
        layer.open({
            type:1,
            title:false,
            btn:['查看机器学习效果提升比率','close'],
            btn1:function(index,layero){
                layer.msg("<i class=\"layui-icon layui-anim layui-anim-rotate layui-anim-loop\">&#xe63d</i>");
                //为了能够显示等待动画
                setTimeout(function () {
                    var timeArray=analyzeSequence(routeSequence);
                    var num=100*(timeArray[1]-timeArray[0])/timeArray[1];
                    num=num.toFixed(1);
                    // layer.open({
                    //     id:'waitingLayer',
                    //     btn:['okay'],
                    //     title:"Message",
                    //     content:"<i class=\"layui-icon layui-anim layui-anim-rotate layui-anim-loop\">&#xe63d</i>"
                    // });

                    layer.alert(
                        "机器学习方法的路径时间预估：<span style='color: red'>"+transferSecondToTime(parseInt(timeArray[0]))+"</span><br>" +
                        "非机器学习方法的时间预估: <span style='color: red'>"+transferSecondToTime(parseInt(timeArray[1]))+"</span><br>" +
                        "预估节省时间比例: <span style='color: red'>"+(num)+"%</span>",
                        {title:'Message',btn:'okay'});
                },100);

            },
            btn2:function(index,layero){
                layer.closeAll();
            },
            closeBtn:0,
            id:'routePlanLayui_layer',
            area:['700px','580px'],
            shade:0.1,
            move:false,
            content: layerContent
        });
    }




    //给路径框增加内容
    var routeBoxContent="<div id='detailedRoute'>";
    for(var i=0;i<routeSequence.length;i++){
        if(i!==routeSequence.length-1){
            if(checkInArray(routeSequence[i].id,obligatoryPlaces)){
                routeBoxContent=routeBoxContent+"<span style='color: red'>"+routeSequence[i].id+"</span>"+" > ";
            }
            else {
                routeBoxContent=routeBoxContent+routeSequence[i].id+" > ";
            }

        }
        else{
            if(checkInArray(routeSequence[i].id,obligatoryPlaces)){
                routeBoxContent=routeBoxContent+"<span style='color: red'>"+routeSequence[i].id+"</span>"
            }
            else {
                routeBoxContent=routeBoxContent+routeSequence[i].id;
            }

        }

    }
    $("#detailedRouteContainer").html(routeBoxContent+"</div>");

    //详细路径链接
    $("#showRouteWithTimeLinkContainer a:eq(0)").on('click',function () {
        // alert("点击了帮助链接");
        if(showDetailedLinkCount%2===0){
            var routeBoxContent_detailed="<div id='detailedRoute'>";
            for(var i=0;i<routeSequence.length;i++){
                if(i!==routeSequence.length-1){
                    if(checkInArray(routeSequence[i].id,obligatoryPlaces)){
                        routeBoxContent_detailed=routeBoxContent_detailed+"<span style='color: red'>"+routeSequence[i].id+" ("+transferSecondToTime(routeSequence[i].time)+")</span>"+" > ";
                    }
                    else {
                        routeBoxContent_detailed=routeBoxContent_detailed+routeSequence[i].id+" > ";
                    }

                }
                else{
                    if(checkInArray(routeSequence[i].id,obligatoryPlaces)){
                        routeBoxContent_detailed=routeBoxContent_detailed+"<span style='color: red'>"+routeSequence[i].id+" ("+transferSecondToTime(routeSequence[i].time)+")</span>"
                    }
                    else {
                        routeBoxContent_detailed=routeBoxContent_detailed+routeSequence[i].id;
                    }
                }
            }
            $(this).html("Show simplified route");
            $("#detailedRouteContainer").html(routeBoxContent_detailed+"</div>");
        }
        else{
            var routeBoxContent="<div id='detailedRoute'>";
            for(var i=0;i<routeSequence.length;i++){
                if(i!==routeSequence.length-1){
                    if(checkInArray(routeSequence[i].id,obligatoryPlaces)){
                        routeBoxContent=routeBoxContent+"<span style='color: red'>"+routeSequence[i].id+"</span>"+" > ";
                    }
                    else {
                        routeBoxContent=routeBoxContent+routeSequence[i].id+" > ";
                    }
                }
                else{
                    if(checkInArray(routeSequence[i].id,obligatoryPlaces)){
                        routeBoxContent=routeBoxContent+"<span style='color: red'>"+routeSequence[i].id+"</span>"
                    }
                    else {
                        routeBoxContent=routeBoxContent+routeSequence[i].id;
                    }
                }
            }
            $(this).html("展示路径<cite>（动态时间窗）</cite>");
            $("#detailedRouteContainer").html(routeBoxContent+"</div>");
        }
        showDetailedLinkCount++;
    });

    //给拓扑图框增加内容
    var allPlacesCollector=[];  //存放所有任务点所有信息
    var longitudeCollector=[];  //存放所有经度信息
    var latitudeCollector=[];   //存放所欲纬度信息
    $.ajax({
        type:"get",
        // url:"http://localhost:8779/edge/fp",
        url:"http://"+domainIp+':' + port + '/task-assign/single-route-plan/findAllPlaces',
        async:false,
        dataType:"json",
        success:function (rcvDataJson) {
            if (rcvDataJson.code===200){
                for (var oneData of rcvDataJson.data) {
                    allPlacesCollector.push(oneData);
                    longitudeCollector.push(oneData.jing);
                    latitudeCollector.push(oneData.wei);
                }
            }
            else{
                layer.alert(rcvDataJson.msg,{
                    title:'Message',btn:'okay'
                });
            }
        },
        error:function (errorInfo) {
            layer.alert(errorInfo.responseText,{
                title:'Message',btn:'okay'
            });
        }
    });
    //对于经纬度进行排序
    longitudeCollector.sort(function (a,b) {
        return a-b;
    });
    latitudeCollector.sort(function (a,b) {
        return a-b;
    });
    //创建变量用于映射
    var minLongitude=longitudeCollector[0];
    var maxLongitude=longitudeCollector[longitudeCollector.length-1];
    var minLatitude=latitudeCollector[0];
    var maxLatitude=latitudeCollector[latitudeCollector.length-1];
    var maxOffsetScaleTop=13/30;
    var maxOffsetScale=2/5;
    var minContainerXOffset=document.getElementById("routeDiagramContainer").offsetWidth*(-1*maxOffsetScale);
    var maxContainerXOffset=document.getElementById("routeDiagramContainer").offsetWidth*(maxOffsetScale);
    var minContainerYOffset=document.getElementById("routeDiagramContainer").offsetHeight*(-1*maxOffsetScaleTop);
    var maxContainerYOffset=document.getElementById("routeDiagramContainer").offsetHeight*(maxOffsetScale);

    //用于画拓扑图的变量
    var nodes=[];
    var edges=[];
    //填充点集
    for (var i=0;i<allPlacesCollector.length;i++) {
        var oneNodeObj={};
        //标注起点
        if(allPlacesCollector[i].id===routeSequence[0].id){
            if(checkInArray(allPlacesCollector[i].id,obligatoryPlaces)){
                oneNodeObj={
                    id:allPlacesCollector[i].id,
                    label:"P "+allPlacesCollector[i].id+"\nSTART",
                    // title:"Place ID: "+allPlacesCollector[i].id,
                    x:mapXToY(allPlacesCollector[i].jing,minLongitude,maxLongitude,minContainerXOffset,maxContainerXOffset),
                    y:mapXToY(allPlacesCollector[i].wei,minLatitude,maxLatitude,minContainerYOffset,maxContainerYOffset),
                    shape:'diamond',
                    color:{
                        border:'white',
                        background:'greenyellow',
                        hover:{
                            border:'white',
                            background:'forestgreen'
                        },
                        highlight:{
                            border:'black',
                            background:'forestgreen'
                        }
                    },
                    physics: false,
                    shadow: true,
                    fixed:true
                };
            }
            else{
                oneNodeObj={
                    id:allPlacesCollector[i].id,
                    label:"P "+allPlacesCollector[i].id+"\nSTART",
                    // title:"Place ID: "+allPlacesCollector[i].id,
                    x:mapXToY(allPlacesCollector[i].jing,minLongitude,maxLongitude,minContainerXOffset,maxContainerXOffset),
                    y:mapXToY(allPlacesCollector[i].wei,minLatitude,maxLatitude,minContainerYOffset,maxContainerYOffset),
                    shape:'dot',
                    color:{
                        border:'white',
                        background:'greenyellow',
                        hover:{
                            border:'white',
                            background:'forestgreen'
                        },
                        highlight:{
                            border:'black',
                            background:'forestgreen'
                        }
                    },
                    physics: false,
                    shadow: true,
                    fixed:true
                };
            }
        }
        //标注必经节点
        else if(allPlacesCollector[i].id!==routeSequence[0].id&&checkInArray(allPlacesCollector[i].id,obligatoryPlaces)){
            oneNodeObj={
                id:allPlacesCollector[i].id,
                label:"P "+allPlacesCollector[i].id,
                // title:"Place ID: "+allPlacesCollector[i].id,
                x:mapXToY(allPlacesCollector[i].jing,minLongitude,maxLongitude,minContainerXOffset,maxContainerXOffset),
                y:mapXToY(allPlacesCollector[i].wei,minLatitude,maxLatitude,minContainerYOffset,maxContainerYOffset),
                shape:'diamond',
                color:{
                    border:'white',
                    background:'orangered',
                    hover:{
                        border:'white',
                        background:'red'
                    },
                    highlight:{
                        border:'black',
                        background:'red'
                    }
                },
                physics: false,
                shadow: true,
                fixed:true
            };
        }
        //标注备选节点
        else if(allPlacesCollector[i].id!==routeSequence[0].id&&
            !checkInArray(allPlacesCollector[i].id,obligatoryPlaces)&&
            checkInArray(allPlacesCollector[i].id,selectablePlaces)){
            oneNodeObj={
                id:allPlacesCollector[i].id,
                label:"P "+allPlacesCollector[i].id,
                // title:"Place ID: "+allPlacesCollector[i].id,
                x:mapXToY(allPlacesCollector[i].jing,minLongitude,maxLongitude,minContainerXOffset,maxContainerXOffset),
                y:mapXToY(allPlacesCollector[i].wei,minLatitude,maxLatitude,minContainerYOffset,maxContainerYOffset),
                shape:'dot',
                color:{
                    border:'white',
                    background:'royalblue',
                    hover:{
                        border:'white',
                        background:'blue'
                    },
                    highlight:{
                        border:'black',
                        background:'blue'
                    }
                },
                physics: false,
                shadow: true,
                fixed:true
            };
        }
        //标注未经过节点
        else{
            oneNodeObj={
                id:allPlacesCollector[i].id,
                label:"P "+allPlacesCollector[i].id,
                // title:"Place ID: "+allPlacesCollector[i].id,
                x:mapXToY(allPlacesCollector[i].jing,minLongitude,maxLongitude,minContainerXOffset,maxContainerXOffset),
                y:mapXToY(allPlacesCollector[i].wei,minLatitude,maxLatitude,minContainerYOffset,maxContainerYOffset),
                shape:'dot',
                color:{
                    border:'white',
                    background:'grey',
                    hover:{
                        border:'white',
                        background:'dimgrey'
                    },
                    highlight:{
                        border:'black',
                        background:'dimgrey'
                    }
                },
                physics: false,
                shadow: true,
                fixed:true
            };
        }
        nodes.push(oneNodeObj);
    }
    //填充所有线段
    for (var i=0;i<routeSequence.length-1;i++) {
        var oneEdgeObj={
            from:routeSequence[i].id,
            to:routeSequence[i+1].id,
            arrows:'to',
            color:{
                color:'deepskyblue',
            },
            chosen:false,
            dashes:false
        };
        //判断是否为回到起点的线段
        if(i===(routeSequence.length-2)&&routeSequence[0].id===routeSequence[routeSequence.length-1].id){
            oneEdgeObj={
                from:routeSequence[i].id,
                to:routeSequence[i+1].id,
                arrows:'to',
                color:{
                    color:'pink',
                },
                // label:'return to start',
                dashes:true,
                chosen:false
            }
        }
        edges.push(oneEdgeObj);
    }
    //创建container, data, options变量完成拓扑图
    var container=document.getElementById("routeDiagramContainer");
    var data={
        nodes:nodes,
        edges:edges
    };
    var options={
        interaction:{
          dragView:false,
          zoomView:false,
          hover:true,
          hoverConnectedEdges:false,
          selectConnectedEdges:false
        },
        physics:true,
        nodes:{
            shape:'dot',
            size:15,
            font:{
                size:10,
                color:'black'
            },
            borderWidth:1.5,
            shadow:true,
        },
        edges:{
            smooth:{
                type:"continuous",
                roundness:0.2
            },
            shadow:true,
            width:1,
            // color: {
            //     color:'deepskyblue'
            // }
        }
    };
    var network=new vis.Network(container,data,options);

    //给拓扑图增加监听
    network.on('hoverNode',function (params) {
        // console.log(params);
        var content="";
        //必经节点tips信息
        if(checkInArray(params.node,obligatoryPlaces)){
            content=
                "<div id='tipsWords'>" +
                "   Place ID: <span>" +params.node+"</span><br>"+
                "   Task Description: <span>"+routeSequence[getIndexInObjArray(params.node,routeSequence)].taskName+"</span><br>" +
                "   Task Property: <span>Obligatory Task</span><br>" +
                "   Estimated Time: <span>"+transferSecondToTime(routeSequence[getIndexInObjArray(params.node,routeSequence)].time)+"</span>"+
                "</div>";
        }
        //备选节点tips信息
        else if (!checkInArray(params.node,obligatoryPlaces)&&checkInArray(params.node,selectablePlaces)){
            content=
                "<div id='tipsWords'>" +
                "   Place ID: <span>" +params.node+"</span><br>"+
                "   Task Description: <span>"+allPlacesSequence[getIndexInObjArray(params.node,allPlacesSequence)].taskName+"</span><br>" +
                "   Task Property: <span>Optional Task</span>" +
                "</div>";

        }
        //未经过节点tips信息
        else {
            content=
                "<div id='tipsWords'>" +
                "   Place ID: <span>" +params.node+"</span><br>"+
                "   Task Description: <span>"+allPlacesSequence[getIndexInObjArray(params.node,allPlacesSequence)].taskName+"</span><br>" +
                "   Task Property: <span>Unaccessable Task</span>" +
                "</div>";
        }
        layer.open({
            type:1,
            title:false,
            closeBtn:false,
            id:'routeDiagramTipsLayer',
            btn:false,
            shade:0,
            offset:[(params.event.pageY)+'px',
                    (params.event.pageX+10)+'px'],
            content:content
        })
    });
    network.on('blurNode',function (params) {
       layer.close(layer.index);
    });

}

function checkInArray(value,array){
    var check=false;
    for (var i=0;i<array.length;i++){
        if(value===array[i]){
            check=true;
            break;
        }
    }
    return check;
}

function mapXToY(value,x1,x2,y1,y2){
    var k=(y2-y1)/(x2-x1);
    var b=(x2*y1-x1*y2)/(x2-x1);
    return k * value + b;
}

function getIndexInObjArray(value,objArray) {
    var index=0;
    for(var i=0;i<objArray.length;i++){
        if(value===objArray[i].id){
            index=i;
            break;
        }
    }
    return index;
}

function transferSecondToTime(totalSeconds){
    var time_hour=Math.floor(totalSeconds/3600);
    var time_minute=Math.floor((totalSeconds-time_hour*3600)/60);
    var time_second=Math.floor(totalSeconds-time_hour*3600-time_minute*60);
    var resultTime="";
    if(time_hour!==0){
        resultTime=time_hour+"h"+time_minute+"min";
    }
    else if(time_hour===0&&time_minute!==0){
        resultTime=time_minute+"min";
    }
    else if(time_minute===0){
        resultTime=time_second+"sec";
    }
    return resultTime;
}

function analyzeSequence(machineSequence){
    var returnMode=0;
    var noMachineSequence=[];
    //判断返回模式
    if(machineSequence[0].id===machineSequence[machineSequence.length-1].id){
        returnMode=1;
    }
    $.ajax({
        type:"get",
        async:false,
        // url:"http://localhost:8779/edge/opsRoute",
        url:"http://"+domainIp+':' + port + '/task-assign/single-route-plan/opsRoute',
        data:{
            jing:machineSequence[0].jing,
            wei:machineSequence[0].wei,
            returnMode:returnMode,
            machineLearningMode:0
        },
        success:function (rcvSequenceJson) {
            console.log("看我这里");
            console.log(rcvSequenceJson);
            if (rcvSequenceJson.code===200){
                noMachineSequence=rcvSequenceJson.data;
            }
            else{
                layer.alert(rcvSequenceJson.msg,{
                    title:'Message',btn:'okay'
                });
            }
        },
        error:function (errorInfo) {
            layer.alert(errorInfo.responseText,{
                title:'Message',btn:'okay'
            });
        }
    });
    //将序列id收集起来
    var machineSeqIds=[];
    var noMachineSeqIds=[];
    for (let x of machineSequence) {
        machineSeqIds.push(x.id);
    }
    for (let x of noMachineSequence) {
        noMachineSeqIds.push(x.id);
    }
    console.log(machineSeqIds);
    console.log(noMachineSeqIds);

    //得到机器学习和非机器学习时间
    var timeArray=[];
    $.ajax({
        type:"get",
        async:false,
        // url:"http://localhost:8779/edge/analyzeTime",
        url:"http://"+domainIp+':' + port + '/task-assign/single-route-plan/analyzeTime',
        data:{
            machineSeqIds:machineSeqIds,
            noMachineSeqIds:noMachineSeqIds
        },
        success:function (rcvTimeArrayJson) {
            if (rcvTimeArrayJson.code===200){
                timeArray=rcvTimeArrayJson.data;
            }
            else{
                layer.alert(rcvTimeArrayJson.msg,{
                    title:'Message',btn:'okay'
                });
            }
        },
        error:function (errorInfo) {
            layer.alert(errorInfo.responseText,{
                title:'Message',btn:'okay'
            });
        }
    });
    return timeArray;

}
